package servlet;

import entity.Data;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import util.JdbcUtil;
import util.JsonUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet("/query")
public class QueryServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("QueryServlet.service()");

        response.setContentType("application/json;charset=utf-8");

        PrintWriter out=response.getWriter();


        String key=request.getParameter("key");


        List<Data> dataList=new ArrayList<>();

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);


            String sql=new StringBuffer()
                    .append("select * ")
                    .append("from t_data ")
                    .append("where message like ? ")
                    .append("or keywords like ? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setString(1,key+"%");
            ps.setString(2,key+"%");

            rs=ps.executeQuery();

            while(rs.next()){
                Data data=new Data();
                data.setId(rs.getInt("id"));
                data.setMessage(rs.getString("message"));
                dataList.add(data);
            }

            con.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(rs,ps,con);
        }



        out.println(JsonUtil.toJson(dataList));





    }
}
